package com.oppodowngrader;

import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 日志工具类，用于记录应用日志和提供UI显示
 */
public class LogUtils {
    private static final String TAG = "OppoDowngrader";
    private static final int MAX_LOG_SIZE = 100;
    private static final List<LogEntry> logEntries = new ArrayList<>();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    
    /**
     * 记录普通日志
     */
    public static void d(String message) {
        Log.d(TAG, message);
        addLogEntry("INFO", message);
    }
    
    /**
     * 记录错误日志
     */
    public static void e(String message, Throwable throwable) {
        Log.e(TAG, message, throwable);
        addLogEntry("ERROR", message + (throwable != null ? ": " + throwable.getMessage() : ""));
    }
    
    /**
     * 记录重要事件
     */
    public static void event(String message) {
        Log.i(TAG, "EVENT: " + message);
        addLogEntry("EVENT", message);
    }
    
    /**
     * 添加日志条目
     */
    private static synchronized void addLogEntry(String level, String message) {
        String timestamp = dateFormat.format(new Date());
        logEntries.add(new LogEntry(timestamp, level, message));
        
        // 限制日志条目数量
        if (logEntries.size() > MAX_LOG_SIZE) {
            logEntries.remove(0);
        }
    }
    
    /**
     * 获取所有日志条目
     */
    public static synchronized List<LogEntry> getLogEntries() {
        return new ArrayList<>(logEntries);
    }
    
    /**
     * 清除所有日志
     */
    public static synchronized void clearLogs() {
        logEntries.clear();
    }
    
    /**
     * 日志条目类
     */
    public static class LogEntry {
        private final String timestamp;
        private final String level;
        private final String message;
        
        public LogEntry(String timestamp, String level, String message) {
            this.timestamp = timestamp;
            this.level = level;
            this.message = message;
        }
        
        public String getTimestamp() {
            return timestamp;
        }
        
        public String getLevel() {
            return level;
        }
        
        public String getMessage() {
            return message;
        }
        
        @Override
        public String toString() {
            return timestamp + " [" + level + "] " + message;
        }
    }
}